package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jumper.chart.ADFetalHeartPlayChart;
import com.jumper.chart.FHRAndTocoPlayChartView;
import com.jumper.chart.ScrollListener;
import com.jumper.chart.detail.FetalRecords;
import com.nostra13.universalimageloader.utils.L;
import com.xn.app.muying.R;
import com.xn.app.muying.bean.FetalMovementInfo;
import com.xn.app.muying.bean.ReXinLvXX;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Request;

/**
 * 历史胎心详情
 */
public class TaiXinXIangXiActivity extends BaseActivity {
    ADFetalHeartPlayChart playChart;
    TextView shi_chang, tai_xin, tai_dong, lu_zhi_shi_jian;
    FHRAndTocoPlayChartView chartView;
    private ArrayList<FetalRecords> fetalMovementInfos = new ArrayList<>();
    //数据库
    private DBManager db = null;
    LinearLayout linearlayout;
    ReXinLvXX relmsg;
    /**
     * 动画
     */
    private AlphaAnimation appearAnimation = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tai_xin_xiang_xi);
        db = new DBManager(this);
        shi_chang = (TextView) findViewById(R.id.shi_chang);
        tai_xin = (TextView) findViewById(R.id.tai_xin);
        tai_dong = (TextView) findViewById(R.id.tai_dong);
        lu_zhi_shi_jian = (TextView) findViewById(R.id.lu_zhi_shi_jian);
        linearlayout = (LinearLayout) findViewById(R.id.linearlayout);
        findViewById(R.id.guan_bi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        appearAnimation = new AlphaAnimation(0, 1);
        appearAnimation.setFillAfter(true);
        appearAnimation.setDuration(1000);
        huoqushuju();
    }


    AlertDialog zhuce_dialog;

    void huoqushuju() {
        zhuce_dialog = new MyAlertDialog().ShowDialog(TaiXinXIangXiActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.HuoQuXinLvXiangXi + "/" + getIntent().getStringExtra("id")).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    if (code == 204 || code == 200) {
                        Type type0 = new TypeToken<ReXinLvXX>() {
                        }.getType();
                        relmsg = new Gson().fromJson(bodys, type0);
                        Message msg2 = new Message();
                        msg2.what = 0;
                        handler.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    zhuce_dialog.dismiss();
                    /**暂行解决方案*/
                    playChart = (ADFetalHeartPlayChart) findViewById(R.id.tai_xin_tu);
                    chartView = playChart.getPlayChartView();
                    chartView.setHaveToco(true);
                    playChart.setScrollListener(new ScrollListener() {
                        @Override
                        public void onScroll(int i) {
                            //滑动中的监听
//                            try {
//                                if (relmsg.getFhRs().get(i) != null) {
//                                    tai_xin.setText(relmsg.getFhRs().get(i) + "");
//                                }
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
                            L.e("滑动中的监听------------->" + i);
                        }

                        @Override
                        public void onScrollStop(int i) {
                            chartView.findFocus();
                            L.e("滑动停止的监听------------>" + i);
                        }
                    });
                    shi_chang.setText(relmsg.getRecordSeconds());
                    tai_xin.setText(relmsg.getAvarageFHRs() + "");
                    tai_dong.setText(relmsg.getKeepScore() + "次");
                    lu_zhi_shi_jian.setText(relmsg.getRecordDate().replace("T", " "));
                    //填充胎心图
                    if (relmsg.getFhRs().size() > 0) {
                        chartView.addData(relmsg.getFhRs(), null);
                    }
                    //计算胎动
                    if (relmsg.getfetalMoveValues() != null & relmsg.getfetalMoveValues().size() > 0) {
                        for (int i = 0; i < relmsg.getfetalMoveValues().size(); i++) {
                            fetalMovementInfos.add(new FetalMovementInfo(relmsg.getfetalMoveValues().get(i).get("time")));
                        }
                        //绘制胎动，传入 胎动 的  列表
                        chartView.addFetalMoveData(fetalMovementInfos);
                    }
                    break;
                case 1:
                    zhuce_dialog.dismiss();
                    if (400 <= msg.arg1 && msg.arg1 < 500) {
                        ToastUtil.showToast(TaiXinXIangXiActivity.this, "修改失败");
                    } else {
                        Type type = new TypeToken<HashMap<String, Object>>() {
                        }.getType();
                        HashMap<String, Object> errmsg = new Gson().fromJson(msg.obj.toString(), type);
                        Type type2 = new TypeToken<HashMap<String, String>>() {
                        }.getType();
                        HashMap<String, String> error = new Gson().fromJson(errmsg.get("error").toString(), type2);
                        ToastUtil.showToast(TaiXinXIangXiActivity.this, error.get("message"));
                    }
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
